import io, base64

from flask import Flask, Blueprint, request, make_response, send_file, json, jsonify

from PIL import Image, ImageDraw, ImageFont

app = Flask(__name__, template_folder='templates', static_folder='static')
# app.url_map.strict_slashes = False
url_prefix = '/nginx_custom_url/'


@app.route('/')
def index():
	return 'hello world!'


# file_path = 'file_exchange/' + file.filename	#设置存储路径
# file.save(file_path)	#保存文件
@app.route(url_prefix + 'upload/', methods=['post', 'get'])
def axp_upload():
	file = request.files.get('file')
	if file is None:
		# return make_response('文件上传失败，服务器未接收到文件', 400)
		pass
	# # # do something here... # # #

	image_byte = file.read()  # filestorage对象转二进制
	image = Image.open(io.BytesIO(image_byte))  # 二进制转Image对象
	width = image.size[0]
	height = image.size[1]
	image_processed = image.convert("L")  # 去色处理
	fontSize = int(width / 10)
	draw = ImageDraw.Draw(image_processed)
	draw.text(xy=(0, 0),
	          text='myWatermark',
	          font=ImageFont.truetype('arial.ttf', fontSize))

	# # # finish working # # #

	data = '服务器返回的helloworld'  # 自定义返回的文本数字
	# data = {'hello': 'hello', 'name': 'myname', 'text': 'mytext'} # JSON对象也是可以的
	RES = make_response()
	RES.headers['response_textdata'] = json.dumps(data)
	RES.data = convert_pil_image_to_byte_array(image_processed)
	return RES


def convert_pil_image_to_byte_array(img) -> bytes:
	img_byte_array = io.BytesIO()
	img.save(img_byte_array, format='JPEG', subsampling=0, quality=100)
	img_byte_array = img_byte_array.getvalue()
	return img_byte_array


if __name__ == '__main__':
	app.run(host='0.0.0.0', port=5000, debug=True)
